package com.gmics.unifiq.menu;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import com.gmics.android.R;
import com.gmics.unifiq.controller.EntityController;
import com.gmics.unifiq.controller.UserFunctions;
import com.gmics.unifiq.entity.Avatar;
import com.gmics.unifiq.entity.Event;
import com.gmics.unifiq.entity.User;

public class Account extends Activity {
	private ListView accountLV;
	private static String[] OPTIONS;
	private ImageView avatarIcon;
	private EntityController controller = new EntityController();
	private Avatar avatar;
	private ProgressDialog pDialog = null;
	private Bitmap bm;
	private User tempUser;
	private static int CHANGE_AVATAR_REQUEST_CODE = 2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account_layout);
		
		new LoadAccount().execute();
	}
	
    class LoadAccount extends AsyncTask<String, String, String> {
   	 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Account.this);
            pDialog.setMessage("Loading account details...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 

        protected String doInBackground(String... args) {
    		UserFunctions uf = new UserFunctions();
    		HashMap<String, String> user = uf.getUser(Account.this);
    		tempUser = controller.retrieveUser(user.get("uid"));

    		avatar = controller.retrieveAvatar(tempUser.getAvatarID());
			try {
				 URL url = new URL(avatar.getImagePath()); 
				 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				 connection.setRequestMethod("POST");
				 connection.setRequestProperty("Connection", "close"); 
				 connection.connect();
				 bm = BitmapFactory.decodeStream(connection.getInputStream());		
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
            return null;
        }
 
        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
                	ImageView avatarSpeech = (ImageView) findViewById(R.id.avatar_speech);
                	avatarSpeech.setVisibility(View.VISIBLE);
                	avatarIcon = (ImageView) findViewById(R.id.avatar_icon);
                	avatarIcon.setImageBitmap(bm);
    	        	
            		OPTIONS = getResources().getStringArray(R.array.acc_options);
                	
                	accountLV = (ListView) findViewById(R.id.acc_lv);	
                	ArrayAdapter<CharSequence> accountAdapter = new ArrayAdapter<CharSequence>(Account.this, android.R.layout.simple_list_item_1, OPTIONS);
                	accountLV.setAdapter(accountAdapter);
                	
                	accountLV.setOnItemClickListener(new OnItemClickListener(){

            			@Override
            			public void onItemClick(AdapterView<?> adapterView, View v, int pos,
            					long id) {
            				// TODO Auto-generated method stub
            				Bundle b = new Bundle();
        					b.putSerializable("user", tempUser);
            				if (pos == 0){
            					Intent notificationScreen = new Intent(Account.this, Notifications.class);
            					notificationScreen.putExtras(b);
            					startActivity(notificationScreen);
            				}
            				else if (pos == 1){
            					Intent loyaltyPointsScreen = new Intent(Account.this, LoyaltyPoints.class);
            					loyaltyPointsScreen.putExtra("avatarBitmap", bm);
            					startActivity(loyaltyPointsScreen);
            				}
            				else if (pos == 2){
            					b.putSerializable("avatar", avatar);
            					Intent changeAvatarScreen = new Intent(Account.this, ChangeAvatar.class);
            					changeAvatarScreen.putExtras(b);
            					startActivityForResult(changeAvatarScreen, CHANGE_AVATAR_REQUEST_CODE);
            				}
            			}
                		
                	});
                }
            });
            
        }
    }
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
    	if (requestCode == CHANGE_AVATAR_REQUEST_CODE){
    		if (resultCode == RESULT_OK){ 	        
    		   avatar = (Avatar) data.getExtras().getSerializable("updatedAvatar");
    		   
   			try {
				 URL url = new URL(avatar.getImagePath()); 
				 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				 connection.setRequestMethod("POST");
				 connection.setRequestProperty("Connection", "close"); 
				 connection.connect();
				 bm = BitmapFactory.decodeStream(connection.getInputStream());		
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
   			
   			avatarIcon.setImageBitmap(bm);
    		
    		}
    	}
    }

}
